<template>
  <div class="main">
    <div class="conter">
        <!-- 个人信息展示 -->
        <el-descriptions class="margin-top" title="我的信息" :column="3">
            <template slot="extra">
                <el-button type="primary" size="small" @click="showEdit">修改</el-button>
                <el-button type="primary" size="small" @click="showNewPassword">修改密码</el-button>
            </template>
            <el-descriptions-item label="用户头像">
                <el-image :src="userinfo.headportrait" style="width: 50px;height: 50px"> </el-image>
            </el-descriptions-item>
            <el-descriptions-item label="用户名">{{ userinfo.name }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ userinfo.telephone }}</el-descriptions-item>
            <el-descriptions-item label="昵称">{{ userinfo.nickname }}</el-descriptions-item>
            <el-descriptions-item label="性别">
                <el-tag size="small">{{ userinfo.gender }}</el-tag>
            </el-descriptions-item>
        </el-descriptions>
        <!-- 我的收货地址 -->
        <h4>我的收货地址</h4>
        <el-button @click="addAddressDialog">添加收货地址</el-button>
        <el-table
        :data="address"
        border
        style="width: 100%">
            <el-table-column prop="name" label="收件人" width="180"></el-table-column>
            <el-table-column prop="city" label="城市"></el-table-column>
            <el-table-column prop="address" label="地址"></el-table-column>
            <el-table-column prop="phone" label="收件人电话"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-link type="primary"  @click="showEditDialog(scope.row)">修改地址</el-link><br/>
                <!-- 删除按钮 -->
                <el-link type="danger"  @click="removeAddressById(scope.row.id)">删除地址</el-link>
                </template>
            </el-table-column>
        </el-table>
        <!-- 修改用户信息界面 -->
        <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%" @close="editDialogClosed">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="90px">
            <el-form-item label="昵称" prop="nickname">
                <el-input v-model="editForm.nickname"></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="name">
                <el-input v-model="editForm.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="editForm.gender">
                <el-radio label="男"></el-radio>
                <el-radio label="女"></el-radio>
            </el-radio-group>
            </el-form-item>
            <el-form-item label="头像" prop="headportrait">
                <el-upload
                    class="avatar-uploader"
                    action="http://localhost:8888/member/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="editForm.headportrait" :src="editForm.headportrait" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="电话" prop="telephone">
                <el-input v-model="editForm.telephone"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editMemberInfo">确 定</el-button>
        </span>
        </el-dialog>
        <!-- 修改用户密码界面 -->
        <el-dialog
        title="修改密码"
        :visible.sync="showNewVisible"
        width="50%"
        @close="passwordClose">
        <el-form ref="passwordRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
              <el-form-item label="旧密码" prop="password">
                <el-input v-model="passwordForm.password" type="password" placeholder="请输入旧密码"></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="password1">
                <el-input type="password" v-model="passwordForm.password1" placeholder="请输入新密码"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="configurePassword">
                <el-input type="password" v-model="passwordForm.configurePassword" placeholder="请确认密码"></el-input>
              </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="showNewVisible = false">取 消</el-button>
            <el-button type="primary" @click="surePassword">确 定</el-button>
        </span>
        </el-dialog>
        <!-- 修改收货地址 -->
        <el-dialog title="收货地址" :visible.sync="dialogFormVisible">
            <el-form :model="addressForm" :rules="addressFormRules" ref="addressFormRef" label-width="130px">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="addressForm.name"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input v-model="addressForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="省市区/县" prop="city">
                <el-cascader collapse-tags="true" :options="cityData" v-model="addressForm.city"></el-cascader>
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
                <el-input v-model="addressForm.address"></el-input>
            </el-form-item>
            <el-form-item label="是否为默认地址" prop="isdefault">
                <el-switch
                    v-model="isdefault"
                    active-color="#13ce66">
                </el-switch>
            </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="editAddress">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 添加收货地址 -->
        <el-dialog title="收货地址" :visible.sync="addFormVisible">
            <el-form :model="addAddressForm" :rules="addAddressFormRules" ref="addAddressFormRef" label-width="130px">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="addAddressForm.name"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input v-model="addAddressForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="省市区/县" prop="city">
                <el-cascader collapse-tags="true" :options="cityData" v-model="addAddressForm.city"></el-cascader>
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
                <el-input v-model="addAddressForm.address"></el-input>
            </el-form-item>
            <el-form-item label="是否为默认地址" prop="isdefault">
                <el-switch
                    v-model="addAddressForm.isdefault"
                    active-color="#13ce66">
                </el-switch>
            </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addAddress">确 定</el-button>
            </div>
        </el-dialog>
        <br/>
    </div>
  </div>
</template>

<script>
import cityData from '../user/order/citydata'
import _ from 'lodash'
export default {
    data() {
        const configurePassword = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请再次输入密码'))
          } else if (value !== this.passwordForm.password1) {
            callback(new Error('两次输入密码不一致!'))
          } else {
            callback()
          }
        }
        return {
            userId: null,
            size: 'medium',
            userinfo: [],
            address: [],
            // 修改用户
            editDialogVisible: false,
            // 修改的信息
            editForm: [],
            editFormRules: {
                nickname: [{ required: true, message: '请输入用户名', trigger: 'blur' },
                           { min: 3, max: 10, message: '用户名的长度在3~10个字符之间', teigger: 'blur' }],
                name: [{ required: true, message: '请输入用户名', trigger: 'blur' },
                       { min: 3, max: 10, message: '用户名的长度在3~10个字符之间', teigger: 'blur' }],
                gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
                headportrait: [{ required: false, message: '请上传头像' }],
                telephone: [{ required: true, message: '联系电话不能为空' },
                           { min: 11, max: 11, message: '联系电话为11字符', teigger: 'blur' }]
            },
            imageUrl: '',
            // 修改密码
            showNewVisible: false,
            passwordForm: {
                password: '',
                configurePassword: ''
            },
            passwordRules: {
                password: [{ required: true, message: '请输入密码', trigger: 'blur' },
                       { min: 6, max: 15, message: '密码的长度在6~15个字符之间', trigger: 'blur' }],
                password1: [{ required: true, message: '请输入密码', trigger: 'blur' },
                       { min: 6, max: 15, message: '密码的长度在6~15个字符之间', trigger: 'blur' }],
                configurePassword: [{
                        validator: configurePassword, trigger: 'blur'
                    }]
            },
            // 修改地址
            addressForm: {
                userid: null,
                name: '',
                phone: '',
                city: '',
                address: '',
                isdefault: false
            },
            addressFormRules: {
                name: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' },
                { min: 2, max: 10, message: '收件人姓名的长度在2~10个字符之间', teigger: 'blur' }],
                phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' },
                { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的联系电话', trigger: 'blur' }],
                city: [{ required: true, message: '请选择省市区县', trigger: 'blur' }],
                address: [{ required: true, message: '请填写详细地址', trigger: 'blur' }]
            },
            cityData,
            dialogFormVisible: false,
            isdefault: true,
            // 添加地址
            addFormVisible: false,
            addAddressForm: {
                userid: null,
                name: '',
                phone: '',
                city: '',
                address: '',
                isdefault: true
            },
            addAddressFormRules: {
                name: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' },
                { min: 2, max: 10, message: '收件人姓名的长度在2~10个字符之间', teigger: 'blur' }],
                phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' },
                { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的联系电话', trigger: 'blur' }],
                city: [{ required: true, message: '请选择省市区县', trigger: 'blur' }],
                address: [{ required: true, message: '请填写详细地址', trigger: 'blur' }]
            }
        }
    },
    created() {
        this.userId = +window.localStorage.getItem('userID')
        console.log(this.userId)
        this.getUserinfo()
        this.getAddress()
    },
    methods: {
        // 获取用户信息
        async getUserinfo() {
            const { data: res } = await this.$axios.get('/member/' + this.userId)
            console.log(res)
            if (res.code !== 200) {
                return this.$message.error('没有查到你的信息')
            }
            this.userinfo = res.data.memberlist[0]
            this.editForm = res.data.memberlist[0]
        },
        // 获取地址信息
        async getAddress() {
            const { data: res } = await this.$axios.get('/address/selectByUserId/' + this.userId)
            if (res.code !== 200) {
                this.isAddress = true
                return this.$message.error('没有查到你的地址,请创建')
            }
            this.address = res.data.address
            console.log(res)
        },
        // 显示修改用户界面
        showEdit() {
            this.editDialogVisible = true
        },
        // 监控会员修改页面
        editDialogClosed() {
            this.$refs.editFormRef.resetFields()
        },
        // 修改会员信息
        async editMemberInfo() {
            // this.editForm.headportrait = this.imageUrl
            console.log('修改')
            console.log(this.editForm)
            const { data: res } = await this.$axios.put('/member/' + this.userId, {
                  nickname: this.editForm.nickname,
                  name: this.editForm.name,
                  gender: this.editForm.gender,
                  headportrait: this.editForm.headportrait,
                  telephone: this.editForm.telephone
              })
            if (res.code !== 200) {
                return this.$message.error('更改信息错误，请联系管理员')
            }
            this.editDialogVisible = false
            this.$message.success('修改成功')
            this.getUserinfo()
        },
        // 用户头像上传成功的方法
        handleAvatarSuccess(res, file) {
            console.log(res)
            this.editForm.headportrait = res.data.url
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg'
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!')
            }
            if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!')
            }
            return isJPG && isLt2M
        },
        // 显示修改密码
        showNewPassword() {
            this.showNewVisible = true
        },
        // 提交修改密码
        async surePassword() {
            console.log(this.passwordForm)
            const { data: res } = await this.$axios.put('/member/updatePassword/' + this.userId, {
                password: this.passwordForm.password,
                configurePassword: this.passwordForm.configurePassword
            })
            if (res.code !== 200) {
                if (res.code === 400) {
                    const msg = res.data.msg
                    return this.$message.error(`${msg}`)
                }
                return this.$message.error('修改失败')
            }
            console.log(res)
            this.$message.success('修改成功，请重新登录')
            window.localStorage.clear()
            this.$router.push('/login')
        },
        // 监视修改密码框关闭
        passwordClose() {
            this.$refs.passwordRef.resetFields()
        },
        // 删除会员地址按钮事件
        async removeAddressById(id) {
            console.log(id)
        // 弹框提示用户是否删除
        const confirmResult = await this.$confirm('此操作将永久删除该地址，是否继续？', '删除地址', {
            confirmButtonText: '',
            cancelButtonText: '',
            type: 'warning'
        }).catch(err => err)
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除 ')
            }
            const { data: res } = await this.$axios.delete('/address/delete/' + id)
            if (res.code !== 200) {
                return this.$message.error('删除失败！ ')
            }
            this.$message.success('删除地址成功！ ')
            this.getAddress()
        },
        // 显示修改地址框
        showEditDialog(row) {
            this.addressForm = row
            this.dialogFormVisible = true
        },
        // 修改地址的方法
        async editAddress() {
            const form = _.cloneDeep(this.addressForm)
            if (this.isdefault) {
                form.isdefault = '是'
            } else {
                form.isdefault = '否'
            }
            form.city = this.addressForm.city.join('')
            const { data: res } = await this.$axios.put('/address/update/' + this.addressForm.id, {
                userid: form.userId,
                city: form.city,
                address: form.address,
                name: form.name,
                phone: form.phone,
                isdefault: form.isdefault
            })
            if (res.code !== 200) {
                return this.$message.error('更新失败')
            }
            this.$message.success('更新成功')
        },
        // 添加收货地址界面
        addAddressDialog() {
            this.addFormVisible = true
        },
        // 确认添加收货地址
        async addAddress() {
            const form = _.cloneDeep(this.addAddressForm)
            if (this.addAddressForm.isdefault) {
                form.isdefault = '是'
            } else {
                form.isdefault = '否'
            }
            form.city = this.addAddressForm.city.join('')
            form.userid = this.userId
            console.log(form)
            const { data: res } = await this.$axios.post('/address/add', form)
            if (res.code !== 200) {
                return this.$message.error('创建地址失败,请重试')
            }
            this.$message.success('添加地址成功')
            this.getAddress()
            this.addFormVisible = false
        }
    }
}
</script>

<style lang="less" scoped>
.main {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
.conter {
    width: 1200px;
}
.el-descriptions {
    margin: 10px;
}
// 用户头像
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
